<template>
  <div>
    <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="2-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="2-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <!-- 下拉框循环请求回来的数据,填充的数组 -->
          <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="2-500个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployeeSimple } from '@/api/employess'
import { addDepartments, getDepartDetail, updateDepartmentById } from '@/api/department'
export default {
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    orginList: {
      type: Array,
      required: true
    }

  },

  data() {
    // 自定义校验编码,不能与现有编码一致
    const validCode = (rule, value, callback) => {
      // value就是当前用户输入的编码,他不能与现有编码重复(originList)
      let codeList = null
      if (this.isEdit) {
        // filter: 过滤出「除了」正在编辑的部门以外的所有部门,获得他们的code
        codeList = this.orginList.filter(item => item.id !== this.id).map(({ code }) => code)
      } else {
        // 遍历这个数组,看输入的code与已有的code是否有一样的
        codeList = this.orginList.map(({ code }) => code)
      }
      // 利用includes,寻找用户当前输入的数据与过滤出来的数据是否一致
      codeList.includes(value) ? callback(new Error('编码' + value + '已经存在')) : callback()
    }

    // 解决需求2:编辑时,通过找到兄弟部门,并判断是否在其中
    // 自定义校验名字,if里面判断同级名字不能重复,else判断子级名字不能重复
    const validateName = (rule, value, callback) => {
      // filter: 过滤出当前所有子部门的名字
      let nameList = null
      if (this.isEdit) {
        // 根据点击当前的部门的id找到他的pid
        const pid = this.orginList.find(item => item.id === this.id).pid
        // 根据pid过滤出所有的子部门,把自己排除在外
        nameList = this.orginList.filter(item => item.pid === pid && item.id !== this.id).map(({ name }) => name)
      } else {
        nameList = this.orginList.filter(item => item.pid === this.id).map(({ name }) => name)
      }
      // 利用includes,寻找用户当前输入的数据与过滤出来的数据是否一致
      nameList.includes(value) ? callback(new Error('部门' + value + '已经存在')) : callback()
    }

    return {
      employees: [],
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2~10个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 50, message: '请输入2~50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' },
          { min: 2, max: 50, message: '请输入2~50个字符', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 2, max: 500, message: '请输入2~500个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployee()
    this.getDepartDetailList()
  },
  methods: {
    // 获取部门详情,编辑部门
    async getDepartDetailList() {
      if (!this.isEdit) return
      const res = await getDepartDetail(this.id)
      // 数据回填
      this.form = res.data
    },
    // 获取下拉员工数据,选取部门负责人
    async loadEmployee() {
      try {
        const res = await getEmployeeSimple()
        this.employees = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 添加或编辑部门
    hSubmit() {
      this.$refs.deptForm.validate(async valid => {
        if (!valid) return
        try {
          let res = null
          // 如果isEdit为true就发送编辑请求,否则就发送添加请求
          if (this.isEdit) {
          // isEdit为ture发送编辑请求
            res = await updateDepartmentById(this.form)
          } else {
          // 否则发送添加请求
            this.form.pid = this.id
            res = await addDepartments(this.form)
          }
          this.$message.success(res.message)
          this.$emit('success')
        } catch (e) {
          this.$message.error(e.message)
        }
      })
    },
    hCancel() {
      this.$emit('callOff')
    }
  }
}

</script>
